package com.ylxn.config;

import com.ylxn.pojo.BoundSql;
import com.ylxn.pojo.Configuration;
import com.ylxn.pojo.MappedStatement;
import com.ylxn.utils.GenericTokenParser;
import com.ylxn.utils.ParameterMapping;
import com.ylxn.utils.ParameterMappingTokenHandler;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class SimpleExecutor implements Executor {
    @Override
    public <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object... params) throws SQLException, ClassNotFoundException, NoSuchFieldException, IllegalAccessException, IntrospectionException, InvocationTargetException, InstantiationException {
        //1,注册驱动
        Connection connection = configuration.getDataSource().getConnection();
        //2,获取sql语句
        String sql = mappedStatement.getSql();
        BoundSql boundSql = getBoundSql(sql);
        //3,获取预处理对象，PreparedStatement
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());
        //4,设置参数
        //参数类型
        String  paramterType= mappedStatement.getParamterType();
        //返回结果类型
        Class<?> paramterClass =  getClassType(paramterType);
        String resultType = mappedStatement.getResultType();
        Class<?> resultClass = getClassType(resultType);
        Object instance = resultClass.newInstance();
        for (int i = 0; i < boundSql.getParameterMappingList().size(); i++) {
            ParameterMapping mapping = boundSql.getParameterMappingList().get(i);
            //#{}内的属性值
            String content = mapping.getContent();
            Field field = paramterClass.getDeclaredField(content);
            //设置暴力访问
            field.setAccessible(true);
            Object o = field.get(params[0]);
            preparedStatement.setObject(i+1,o);
        }

        //5，执行sql
        ResultSet resultSet = preparedStatement.executeQuery();
        ArrayList<Object> list = new ArrayList<>();
        //6,封装返回结果集
        while (resultSet.next()){
            //获取结果集元数据
            ResultSetMetaData metaData = resultSet.getMetaData();
            for (int i = 1; i < metaData.getColumnCount(); i++) {
                //字段名
                String columnName = metaData.getColumnName(i);
                //字段的值
                Object object = resultSet.getObject(i);
                //使用反射，根据数据库表和实体的对应关系完成封装
                PropertyDescriptor descriptor = new PropertyDescriptor(columnName, resultClass);
                Method method = descriptor.getWriteMethod();
                method.invoke(instance,object);
            }
            list.add(instance);
        }
        return null;
    }

    private Class<?> getClassType(String paramterType) throws ClassNotFoundException {
        if (paramterType!=null){
            Class<?> aClass = Class.forName(paramterType);
            return aClass;
        }
        return null;
    }

    /**
     * 将#{}使用？代替，解析出#{}里面的值
     * @param sql
     * @return
     */
    private BoundSql getBoundSql(String sql) {
        ParameterMappingTokenHandler handler = new ParameterMappingTokenHandler();
        GenericTokenParser tokenParser = new GenericTokenParser("#{", "}", handler);
        String parse = tokenParser.parse(sql);
        List<ParameterMapping> parameterMappings = handler.getParameterMappings();
        BoundSql boundSql = new BoundSql(parse, parameterMappings);
        return boundSql;
    }
}
